import React, { useState, useRef, useMemo, useCallback, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import WorkReportScreen from '../screens/WorkReportScreen';
import WorkFlowScreen from '../screens/WorkFlowScreen';
import BatchDetailScreen from '../screens/WorkFlowScreen/BatchDetailScreen';
import TaskScreen from '../screens/Task';
import TaskDetailScreen from '../screens/Task/task_detail';

interface CustomTabNavigatorProps {
  onLogout: () => void;
}

type ScreenType = 'WorkReport' | 'Task' | 'WorkFlow' | 'BatchDetail' | 'TaskDetail';

interface ScreenState {
  type: ScreenType;
  params?: any;
}

const CustomTabNavigator: React.FC<CustomTabNavigatorProps> = ({ onLogout }) => {
  const insets = useSafeAreaInsets();
  const [screenStack, setScreenStack] = useState<ScreenState[]>([
    { type: 'WorkReport' }
  ]);

  // 使用 useRef 保持组件实例，确保真正的缓存
  const componentInstancesRef = useRef<Map<string, React.ReactElement>>(new Map());

  // 缓存所有页面，但只显示当前页面
  const [allScreens, setAllScreens] = useState<Map<string, React.ReactElement>>(new Map());

  // 当前显示的页面
  const currentScreen = screenStack[screenStack.length - 1];

  // 导航函数 - 先定义，避免循环依赖
  const navigateRef = useRef<(screenType: ScreenType, params?: any) => void>(() => { });
  const goBackRef = useRef<() => void>(() => { });

  // 创建或获取组件实例
  const getOrCreateComponent = useCallback((screenType: ScreenType, params?: any): React.ReactElement => {
    const cacheKey = `${screenType}_${JSON.stringify(params || {})}`;
    const shouldCacheComponent = screenType === 'WorkReport' || screenType === 'Task' || screenType === 'WorkFlow';

    if (shouldCacheComponent && componentInstancesRef.current.has(cacheKey)) {
      return componentInstancesRef.current.get(cacheKey)!;
    }

    let component: React.ReactElement;

    switch (screenType) {
      case 'WorkReport':
        component = <WorkReportScreen key={cacheKey} onLogout={onLogout} />;
        break;
      case 'Task':
        component = (
          <TaskScreen
            key={cacheKey}
            onLogout={onLogout}
            navigation={{
              navigate: (type: ScreenType, p?: any) => navigateRef.current?.(type, p),
              goBack: () => goBackRef.current?.(),
            }}
          />
        );
        break;
      case 'WorkFlow':
        component = (
          <WorkFlowScreen
            key={cacheKey}
            onLogout={onLogout}
            navigation={{
              navigate: (type: ScreenType, p?: any) => navigateRef.current?.(type, p),
              goBack: () => goBackRef.current?.(),
            }}
          />
        );
        break;
      case 'BatchDetail':
        component = (
          <BatchDetailScreen
            key={cacheKey}
            route={{ params: params || {} }}
            navigation={{
              goBack: () => goBackRef.current?.(),
            }}
          />
        );
        break;
      case 'TaskDetail':
        component = (
          <TaskDetailScreen
            key={cacheKey}
            route={{ params: params || {} }}
            navigation={{
              goBack: () => goBackRef.current?.(),
            }}
          />
        );
        break;
      default:
        throw new Error(`Unknown screen type: ${screenType}`);
    }

    if (shouldCacheComponent) {
      componentInstancesRef.current.set(cacheKey, component);
    }

    return component;
  }, [onLogout]);

  // 导航到新页面
  const navigate = useCallback((screenType: ScreenType, params?: any) => {
    setScreenStack(prev => [...prev, { type: screenType, params }]);
  }, []);

  // 返回上一页
  const goBack = useCallback(() => {
    setScreenStack(prev => {
      if (prev.length > 1) {
        return prev.slice(0, -1);
      }
      return prev;
    });
  }, []);

  // 切换到指定页面（保持状态）
  const switchToTab = useCallback((screenType: ScreenType) => {
    setScreenStack(prev => {
      // 检查堆栈中是否已存在该页面
      const existingIndex = prev.findIndex(screen => screen.type === screenType);

      if (existingIndex !== -1) {
        // 如果存在，切换到该页面（保持状态）
        return prev.slice(0, existingIndex + 1);
      } else {
        // 如果不存在，添加到堆栈
        return [...prev, { type: screenType }];
      }
    });
  }, [screenStack]);

  // 将导航函数赋值给ref，避免循环依赖
  navigateRef.current = navigate;
  goBackRef.current = goBack;

  // 渲染所有页面，但只显示当前页面（真正的状态保持）
  const renderAllScreens = useCallback(() => {
    const screens: React.ReactNode[] = [];
    const currentPageKey = `${currentScreen.type}_${JSON.stringify(currentScreen.params || {})}`;

    // 渲染所有已缓存的页面（只缓存报工和工单进度）
    allScreens.forEach((component, pageKey) => {
      const isActive = pageKey === currentPageKey;

      screens.push(
        <View
          key={pageKey}
          style={{
            flex: 1,
            display: isActive ? 'flex' : 'none'
          }}
        >
          {component}
        </View>
      );
    });

    // 如果当前页面不需要缓存（如批次详情），直接渲染
    const shouldCache = currentScreen.type === 'WorkReport' || currentScreen.type === 'Task' || currentScreen.type === 'WorkFlow';
    if (!shouldCache) {
      const component = getOrCreateComponent(currentScreen.type, currentScreen.params);
      screens.push(
        <View
          key={currentPageKey}
          style={{
            flex: 1,
            display: 'flex'
          }}
        >
          {component}
        </View>
      );
    }

    return screens;
  }, [currentScreen, allScreens, getOrCreateComponent]);

  // 确保当前页面被缓存（只缓存报工和工单进度页面）
  useEffect(() => {
    const pageKey = `${currentScreen.type}_${JSON.stringify(currentScreen.params || {})}`;

    // 只缓存报工和工单进度页面
    const shouldCache = currentScreen.type === 'WorkReport' || currentScreen.type === 'Task' || currentScreen.type === 'WorkFlow';

    if (shouldCache && !allScreens.has(pageKey)) {
      const component = getOrCreateComponent(currentScreen.type, currentScreen.params);
      setAllScreens(prev => new Map(prev).set(pageKey, component));
    }
  }, [currentScreen, allScreens, getOrCreateComponent]);

  // 只在显示主页面时显示Tab栏
  const showTabBar = currentScreen.type === 'WorkReport' || currentScreen.type === 'Task' || currentScreen.type === 'WorkFlow';

  return (
    <View style={styles.container}>
      {/* 主内容区域 - 渲染所有页面但只显示当前页面 */}
      <View style={styles.content}>
        {renderAllScreens()}
      </View>

      {/* 底部Tab栏 - 只在主页面显示 */}
      {showTabBar && (
        <View style={[styles.tabBar, {
          paddingBottom: Math.max(insets.bottom, 0),
          height: 50 + Math.max(insets.bottom, 0),
          backgroundColor: '#fff', // 确保背景色为白色
        }]}>
          <TouchableOpacity
            style={[
              styles.tabItem,
              currentScreen.type === 'WorkReport' && styles.activeTabItem
            ]}
            onPress={() => switchToTab('WorkReport')}
            activeOpacity={0.7}
          >
            <Text style={[
              styles.tabText,
              currentScreen.type === 'WorkReport' && styles.activeTabText
            ]}>
              报工
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              styles.tabItem,
              currentScreen.type === 'Task' && styles.activeTabItem
            ]}
            onPress={() => switchToTab('Task')}
            activeOpacity={0.7}
          >
            <Text style={[
              styles.tabText,
              currentScreen.type === 'Task' && styles.activeTabText
            ]}>
              任务
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              styles.tabItem,
              currentScreen.type === 'WorkFlow' && styles.activeTabItem
            ]}
            onPress={() => switchToTab('WorkFlow')}
            activeOpacity={0.7}
          >
            <Text style={[
              styles.tabText,
              currentScreen.type === 'WorkFlow' && styles.activeTabText
            ]}>
              工单进度
            </Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  content: {
    flex: 1,
  },
  tabBar: {
    flexDirection: 'row',
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#eee',
    height: 50,
    paddingTop: 0,
  },
  tabItem: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  activeTabItem: {
    // 激活状态的样式
  },
  tabText: {
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
  },
  activeTabText: {
    color: '#007AFF',
    fontWeight: 'bold',
  },
});

export default CustomTabNavigator; 